<?php
// +----------------------------------------------------------------------
// | HkCms 权限菜单模型
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: HkCms team <admin@hkcms.cn>
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\admin\model\auth;

use think\facade\Db;
use think\Model;

class AuthRule extends Model
{
    /**
     * 生成菜单
     * @param $menu array 数组
     * @param string $app 插件名称
     * @return bool
     */
    public function createMenu($menu, $app = '') : bool
    {
        if (empty($menu) || !is_array($menu)) {
            trace("创建菜单失败：菜单数据为空！",'error');
            return false;
        }

        Db::startTrans();
        try {
            // 支持三级
            foreach ($menu as $key=>$value) {
                $value['app'] = $app;

                $tempModel1 = self::create($value);
                if (!empty($value['child'])) {
                    foreach ($value['child'] as $k=>$v) {
                        $v['app'] = $app;
                        $v['parent_id'] = $tempModel1->id;
                        $tempModel2 = self::create($v);

                        if (!empty($v['child'])) {
                            foreach ($v['child'] as $kk=>$vv) {
                                $vv['app'] = $app;
                                $vv['parent_id'] = $tempModel2->id;
                                self::create($vv);
                            }
                        }
                    }
                }
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            trace("创建菜单失败：".$exception->getMessage(),'error');
            return false;
        }
        // 删除菜单缓存
        app('cache')->tag('menu')->clear();
        return true;
    }

    public function setNameAttr($value)
    {
        return strtolower($value);
    }

    public function getTitleLanAttr($value,$data)
    {
        return lang($data['title']);
    }

    /**
     * save 方法下，新增，修改都会触发
     */
    public static function onAfterWrite()
    {
        // 删除菜单缓存
        app('cache')->tag('menu')->clear();
    }

    public static function onAfterDelete()
    {
        app('cache')->tag('menu')->clear();
    }
}
